package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;


/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-27
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper  checkInConfigMapper;


    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }
    /**
     * 申请入住
     *
     * @param checkInApplyDto 入住申请
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.判断老人是否入住
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                                .eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elderLambdaQueryWrapper);

        //1.1如果老人已经入住--报错
        if (elder != null){
            throw new BaseException("老人已经入住，不能再次办理入住");
        }

        //1.2更新床位状态为已入住(代表老人申请的房间的床位状态修改)
        Bed  bed = new Bed();
        bed.setBedStatus(1);
        bed.setRoomId(checkInApplyDto.getCheckInConfigDto().getRoomId());
        bed.setId(checkInApplyDto.getCheckInConfigDto().getBedId());
        bedMapper.updateById(bed);

        //2.新增或者更新老人
        Elder elder1 = insertOrUpdateElder(checkInApplyDto);

        //2.1新增合同办理
        Contract  contract = new Contract();
        BeanUtil.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setStatus(0L);
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setElderId(elder1.getId());
        contract.setElderName(elder1.getName());
        contractMapper.insertContract(contract);


        //2.2新增入住配置
        CheckIn checkIn = new CheckIn();
        BeanUtil.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkIn);
        checkIn.setBedNumber(elder1.getBedNumber());
        checkIn.setElderId(elder1.getId());
        checkIn.setElderName(elder1.getName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setIdCardNo(elder1.getIdCardNo());
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStatus(0);
        checkInMapper.insertCheckIn(checkIn);

        //2.3新增入住信息
        CheckInConfig  checkInConfig = new CheckInConfig();
        BeanUtil.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insertCheckInConfig(checkInConfig);
    }

    private Elder insertOrUpdateElder(CheckInApplyDto checkInApplyDto) {
        Elder elder = new Elder();
        BeanUtil.copyProperties(checkInApplyDto.getCheckInElderDto(), elder);
        elder.setStatus(1);
        elder.setBedId(checkInApplyDto.getCheckInConfigDto().getBedId());
        Bed bed = bedMapper.selectById(elder.getBedId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setCreateTime(DateUtils.getNowDate());
        elder.setUpdateTime(DateUtils.getNowDate());

        //查询判断老人是否存在
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo,elder.getIdCardNo())
                                .eq(Elder::getStatus, 1);
        Elder elder2 = elderMapper.selectOne(elderLambdaQueryWrapper);
        if (elder2 == null){
            elderMapper.insertElder(elder);
        }else {
            elderMapper.updateById(elder);
        }
        return elder;
    }
    /**
     * 入住详情
     *
     * @param id 入住id
     * @Return 入住详情
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        //查询入住表内的信息
        CheckIn checkIn = checkInMapper.selectById(id);
        LocalDateTime  startDate = checkIn.getStartDate();
        LocalDateTime   endDate = checkIn.getEndDate();
        String bedNumber = checkIn.getBedNumber();
        //查询老人表内的信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtil.copyProperties(elder, checkInElderVo);
        String birthday = elder.getBirthday();
        LocalDateTime now = LocalDateTime.now();
        checkInElderVo.setAge((now.getYear() - LocalDate.parse(birthday).getYear())+1);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //查询老人家属表内的信息
        List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();
        elderFamilyVoList=JSONUtil.toList(checkIn.getRemark(), ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        //查询入住配置表内的信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectByCheckInId(checkIn.getId());
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtil.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(startDate);
        checkInConfigVo.setEndDate(endDate);
        checkInConfigVo.setBedNumber(bedNumber);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //查询签约办理表内的信息
        Contract contract = contractMapper.selectByElderId(elder.getId());
        checkInDetailVo.setContract(contract);


        return checkInDetailVo;
    }

}
